package com.srwl.mytx.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.MoonUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.BottomBarBadge;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MessageRecordAdapter extends RecyclerView.Adapter<MessageRecordAdapter.ViewHolder> {
    private static final String TAG = "MessageRecordAdapter";

    private Context context;
    private List<Message> messageList;
    private InteractionListener listener;
    private List<String> idList = new ArrayList<>();//需要下载用户信息的id列表

    public MessageRecordAdapter(Context context, List<Message> messageList) {
        this.context = context;
        this.messageList = messageList;
        Collections.reverse(messageList);
    }

    public void setOnItemClickListener(InteractionListener mOnItemClickListener) {
        this.listener = mOnItemClickListener;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.message_record_item, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        Message message = messageList.get(position);
        String userId;
        User showUser;
        if (Utils.isSendMessage(message)) {//发出的消息，展示登录者用户信息
            showUser = UserProfileManager.getInstance().getLoginUserInfo();
        } else {
            userId = message.getFromId();
            showUser = Helper.getInstance().getContactUserInfo(userId);
        }
        if (showUser != null) {
            GlideLoadUtils.glideLoad(context, showUser.getAvatar(), holder.iv_avatar, R.drawable.tx_default_avatar_1);
            SpannableString spannableString = MoonUtils.replaceEmoticonsAndHighlight(context, showUser.getUsername(), 0.6f, ImageSpan.ALIGN_BOTTOM, null, null);
            holder.tv_name.setText(spannableString);
        }

        holder.motioned.setVisibility(View.GONE);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User targetUser;
                Intent intent = new Intent(context, ChatActivity.class);
                if (Utils.isSendMessage(message)) {
                    targetUser = Helper.getInstance().getContactUserInfo(message.getToId());
                } else {
                    targetUser = showUser;
                }
                if (targetUser == null) {
                    Log.e(TAG, "onClick: 聊天对象为空");
                    return;
                }
                intent.putExtra(Constant.EXTRA_TARGET_USER_INFO, targetUser);
                intent.putExtra(Constant.EXTRA_INFO_MESSAGE, message);
//                if (!Helper.getInstance().isNormalContact(userId)) {
//                    intent.putExtra("CONTACT_STATUS", Constant.CONTACT_STATUS_ACTIVE_DELETE);
//                }
                context.startActivity(intent);

            }
        });

        SpannableString spannableString = MoonUtils.replaceEmoticonsAndHighlight(context, message.getContent(), 0.6f, ImageSpan.ALIGN_BOTTOM, message.getHighlightKeyWord(), context.getResources().getColor(R.color.holo_blue_bright));
        holder.tv_message.setText(spannableString);
        holder.time.setText(DateUtils.getTimestampString(message.getCreated()));
        //发送失败，展示红点，用以提示
        if (Utils.isSendMessage(message) && message.getSendState() != null && message.getSendState() == Constant.IM_SEND_STATE_FAIL) {
            holder.msgState.setVisibility(View.VISIBLE);
        } else {
            holder.msgState.setVisibility(View.GONE);
        }


    }


    @Override
    public int getItemCount() {
        return messageList.size();
    }


    private void getUserInfo(final ViewHolder holder, final String userId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        idList.remove(userId);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse:从服务端获取联系人信息出错 " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse:从服务端获取联系人信息出错 " + result.getMsg());

                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();

                        User user = object.toJavaObject(User.class);
                        user.setUId(userId);
                        user.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(user);//作为临时联系人，保存在用户表中

                        GlideLoadUtils.glideLoad(context, user.getAvatar(), holder.iv_avatar, R.drawable.tx_default_avatar_1);

                        holder.tv_name.setText(user.getUsername());

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        idList.remove(userId);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView iv_avatar;
        TextView tv_name;
        TextView tv_message;
        TextView time;
        BottomBarBadge tv_unreadCount;
        View msgState;
        TextView motioned;

        public ViewHolder(View itemView) {
            super(itemView);
            iv_avatar = itemView.findViewById(R.id.avatar);
            tv_name = itemView.findViewById(R.id.name);
            tv_unreadCount = itemView.findViewById(R.id.unread_msg_number);
            tv_message = itemView.findViewById(R.id.tv_message);
            time = itemView.findViewById(R.id.time);
            msgState = itemView.findViewById(R.id.msg_state);
            motioned = itemView.findViewById(R.id.mentioned);
        }

    }

    public interface InteractionListener {
        void onLongClick(int position, Conversation conversation);
    }

}
